<template>
  <div class="analysis">
    <div class="chart-container">
      <span class="analysis_title">最近考试成绩</span>
      <div class="chart-placeholder">
        <div id="echarts_forAnalysis" style="width: 100%; height: 30vh"></div>
      </div>
    </div>
    <div class="chart-container">
      <span class="analysis_title">各科目试卷数量</span>
      <div class="chart-placeholder">
        <div id="echarts_forSubject" style="width: 100%; height: 30vh"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import * as echarts from "echarts";
import testResult from "@/api/questionItem/testResult";
import { useTestAnalysis } from "@/utils/useTestAnalysis";

const { generateChartOption } = useTestAnalysis();

const initEcharts1 = () => {
  const myCharts = echarts.init(document.getElementById("echarts_forAnalysis"));
  myCharts.clear();
  testResult.allAnalysis().then((res) => {
    const option = generateChartOption(
      res.data.xaxis,
      res.data.yaxis,
      res.data.ids
    );
    // 设置自适应
    window.addEventListener("resize", () => {
      myCharts.resize();
    });
    myCharts.setOption(option);
  });
};

const initEcharts2 = () => {
  const myCharts = echarts.init(document.getElementById("echarts_forSubject"));
  myCharts.clear();
  testResult.anglysisNumber().then((res) => {
    let option = {
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} ({d}%)",
      },
      series: [
        {
          type: "pie",
          avoidLabelOverlap: true,
          data: res.data,
          label: {
            show: true,
            formatter: "{b}\n{c}", // 名称和数值分行显示
            position: "outside", // 标签位置改到外部
            fontSize: 12, // 更小的字体
          },
        },
      ],
    };
    // 设置自适应
    window.addEventListener("resize", () => {
      myCharts.resize();
    });
    myCharts.setOption(option);
  });
};

// 清理事件监听器
onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

onMounted(() => {
  initEcharts1();
  initEcharts2();
});
</script>

<style scoped>
.analysis {
  padding: 16px;
}

.chart-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  padding-top: 5px;
  margin: 16px 0;
}

.chart-placeholder {
  height: auto;
  min-height: 200px;
  background-color: #f2f3f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  padding: 10px;
}

.analysis_title {
  font-size: 15px;
  font-weight: bold;
}
</style>
